/**
 * The Community Project
 * Copyright Team1 Productions
 * 
 * Joshua Amick
 * Stephen Cunningham
 * Thema Davis
 * Tomika Dawson
 * Lucie DeCristofaro
 * 
 * All Rights Reserved.
 */

package com.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.constants.UserPermissions;
import com.domain.Profile;
import com.domain.User;
import com.forms.CreateUserForm;
import com.util.CommunityEmailer;

public class SaveUserAction extends CommunityBaseAction{
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.execute(mapping, form, request, response);

		// Cast the actionForm, if there is one.
		
		CreateUserForm f = (CreateUserForm) form;
		ActionForward forward = mapping.findForward("failure");
		User user = (User)request.getSession().getAttribute("AUTH_USER");
		if(user!=null){
			String q = request.getParameter("r");
			if(q!=null&&(!q.equals(""))){
				User updateUser = this.biz.getPrivateMgr().getUserByKeyId(Long.parseLong(q)); 
				Profile p = updateUser.getProfile();
				if(f.getSubscribeToEmails()!=null&&f.getSubscribeToEmails().equals("true")){
					updateUser.setSubscribedToEmails(true);
				}
				else{
					updateUser.setSubscribedToEmails(false);
				}
				if(f.getPublicViewable()!=null&&f.getPublicViewable().equals("true")){
					p.setPublicViewable(true);
				}
				else{
					p.setPublicViewable(false);
				}
				if(f.getIsAdminUser()!=null && f.getIsAdminUser().equals("true")){
					updateUser.setUserPermissions(UserPermissions.ADMIN);
				}
				else{
					updateUser.setUserPermissions(UserPermissions.PUBLIC);
				}
				updateUser.setLastUpdateUser(user);
				p.setFirstName(f.getFirstName());
				p.setLastName(f.getLastName());
				p.setAddress1(f.getAddress1());
				p.setAddress2(f.getAddress2());
				p.setCity(f.getCity());
				p.setEducation(f.getEducation());
				p.setEmployer(f.getEmployer());
				p.setMajor(f.getMajor());
				p.setPhone(f.getPhone());
				p.setPositionDescription(f.getPositionDescription());
				p.setProfessionalOrganizations(f.getProfessionalOrganizations());
				p.setSecondaryEmail(f.getSecondaryEmail());
				p.setStudentOrganizations(f.getStudentOrganizations());
				p.setZip(f.getZip());
				p.setState(f.getState());
				p.setEmploymentStartDate(f.getDateTimestamp(f.getEmpStartYear(), f.getEmpStartMonth(), f.getEmpStartDay()));
				p.setEmployer(f.getEmployer());
				p.setGraduationDate(f.getDateTimestamp(f.getGradYear(), f.getGradMonth(), f.getGradDay()));
				this.biz.getPrivateMgr().getProfileDAO().save(p);
				this.biz.getPrivateMgr().getUserDAO().save(updateUser);
				if(updateUser!=null&&updateUser.getKeyId()>0){
					request.setAttribute("INFO", "User saved successfully.");
					forward = mapping.findForward("success");
					request.setAttribute("RESULT_USER", updateUser);
					return forward;
				}
				else{
					request.setAttribute("ERROR", "Error occurred while saving user.");
					forward = mapping.findForward("failure");
					return forward;
				}	
			}
			else{
				UserPermissions up;
				boolean view;
				boolean subscribed;
				User userInDbase;
				String randomPassword = this.biz.getPrivateMgr().getPasswordForNewUser();
				userInDbase = this.biz.getPrivateMgr().getUserByUsername(f.getUsername());
				CommunityEmailer comEmail = this.biz.getCommunityEmailer();
				if(userInDbase!=null){
					request.setAttribute("ERROR", "Username taken, please select another.");
					forward = mapping.findForward("failure");
					return forward;
				}
				if(f.getIsAdminUser().equals("true")){
					up = UserPermissions.ADMIN;
				}
				else{
					up = UserPermissions.PUBLIC;
				}
				if(f.getPublicViewable().equals("true")){
					view = true;
				}
				else{
					view = false;
				}
				if(f.getSubscribeToEmails()!=null&&f.getSubscribeToEmails().equals("true")){
					subscribed  = true;
				}
				else{
					subscribed = false;
				}
				User newUser = this.biz.getPrivateMgr().saveUser(f.getUsername(), user, f.getEmail(), 
				user, randomPassword, up, false, true, f.getFirstName(), 
				f.getLastName(), f.getAddress1(), f.getAddress2(), f.getCity(), f.getState(), 
				f.getZip(), f.getSecondaryEmail(), f.getPhone(), f.getEmployer(), f.getPositionDescription(), 
				f.getDateTimestamp(f.getEmpStartYear(), f.getEmpStartMonth(), f.getEmpStartDay()), 
				null, f.getMajor(), f.getDateTimestamp(f.getGradYear(), f.getGradMonth(), f.getGradDay()), 
				f.getProfessionalOrganizations(), f.getStudentOrganizations(), view, subscribed);
				if(newUser!=null){
					try{
						comEmail.sendMail(newUser.getEmail(),"Welcome to the Community Project at USC", "Your account information is below." +
								"\nUsername: "+newUser.getUsername()+"\nPassword: "+newUser.getPassword()+"\nThank you for the interest in our site.");
						request.setAttribute("INFO", "User '"+newUser.getUsername()+"' was successfully created and notified.");
					}catch(Exception e){
						request.setAttribute("ERRORS", "Problem sending user notification.");
						forward = mapping.findForward("failure");
					}
				}
				else{
					request.setAttribute("ERRORS", "Problem creating user.");
					forward = mapping.findForward("failure");
				}
			}
						
		}
		else{
			request.setAttribute("ERROR", "Invalid user creditials for saving user.");
			forward = mapping.findForward("failure");
		}

		return forward;
	}
}
